from machine import Pin
from utime import sleep_ms
import ds1302
import onewire
import ds18x20
from machine import SoftI2C
from ssd1306 import SSD1306_I2C

# 1302
week_str = ("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")
# oled
oled_color = (0, 1)
title_pos = (30, 4)
content_pos = (16, 22)
disc = 12

def oled_show(oled, time_list, temp):
    oled.fill(oled_color[0])
    # 标题
    oled.text("RTC-TEMP", title_pos[0], title_pos[1], oled_color[1])
    # 时间
    oled.text(time_list[0], content_pos[0], content_pos[1], oled_color[1])
    oled.text(time_list[1] + " " + time_list[2], content_pos[0], content_pos[1] + disc, oled_color[1])
    # 温度
    oled.text("T: %.2fC" % temp, content_pos[0], content_pos[1] + 2 * disc, oled_color[1])
    oled.show()


def ds1302_time(ds1302):
    time_list = list()
    
    date_time = ds1302.DateTime()
    time_list.append("%d/%d/%d" % (date_time[0], date_time[1], date_time[2]))
    time_list.append("%02d:%02d:%02d" % (date_time[4], date_time[5], date_time[6]))
    time_list.append(week_str[date_time[3]])
    
    return time_list


def ds18b20_temp(ds18b20):
    roms = ds18b20.scan()
    if len(roms):
        ds18b20.convert_temp()
        return ds18b20.read_temp(roms[0])
    else:
        return 0


def device_board(ds1302, ds18b20, oled):
    while True:
        # 读取时间
        time_list = ds1302_time(ds1302)
        # 读取温度
        temp = ds18b20_temp(ds18b20)
        # 数据显示
        oled_show(oled, time_list, temp)
        sleep_ms(200)
    

if __name__ == "__main__":
    # 创建DS1302对象
    ds1302 = ds1302.DS1302(clk=Pin(14), dio=Pin(27), cs=Pin(26))
    ds1302.DateTime([2024, 6, 28, 5, 16, 35, 20])
    # 创建DS18B20对象
    ds18b20 = ds18x20.DS18X20(onewire.OneWire(Pin(25)))
    # 创建OLED对象
    oled = SSD1306_I2C(128, 64, SoftI2C(scl=Pin(18), sda=Pin(23)))

    device_board(ds1302, ds18b20, oled)
    
